package com.sinszm.web.cos;

import cn.hutool.core.util.StrUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.region.Region;
import com.sinszm.common.exception.ApiException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.annotation.Resource;

/**
 * Cos文件存储服务器
 *
 * @author sinszm
 */
@Configuration
@ConditionalOnExpression("${szm.boot.cos.enable:false}")
@PropertySource("classpath:cos.properties")
@EnableConfigurationProperties(CosProperties.class)
public class CosConfiguration {

    @Resource
    private CosProperties cosProperties;

    /**
     * COS客户端
     * <p>
     *     1.需要使用为私有访问；
     *     2.需要设置为标准存储模式；
     *     3.开启SSE-COS加密；
     * </p>
     * @return  客户端对象
     */
    @Bean
    public COSClient cosClient() {
        COSCredentials cred = new BasicCOSCredentials(
                StrUtil.trimToEmpty(cosProperties.getSecretId()),
                StrUtil.trimToEmpty(cosProperties.getSecretKey())
        );
        ClientConfig clientConfig = new ClientConfig(new Region(
                StrUtil.trimToEmpty(cosProperties.getRegion())
        ));
        clientConfig.setHttpProtocol(HttpProtocol.https);
        return new COSClient(cred, clientConfig);
    }

    /**
     * 判断并获取有效存储桶
     *
     * @return  存储桶名称
     */
    @Bean
    public String cosBucketName() {
        String bucketName = StrUtil.trimToEmpty(cosProperties.getBucketName());
        boolean exist = cosClient().doesBucketExist(bucketName);
        if (exist) {
            return bucketName;
        }
        throw new ApiException("存储桶不存在");
    }

}
